package com.nowcoder.community.d_controller;


import com.nowcoder.community.a_entity.DiscussPost;
import com.nowcoder.community.a_entity.Page;
import com.nowcoder.community.c_service.ElasticsearchService;
import com.nowcoder.community.c_service.LikeService;
import com.nowcoder.community.c_service.UserService;
import com.nowcoder.community.z_util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>——————————————————————————————————————————————-————
 * <p> SearchController：搜索框
 * <p>——————————————————————————————————————————————-————
 */
@Controller
public class SearchController implements CommunityConstant{
    @Autowired
    private ElasticsearchService elasticsearchService;
    //其他L<MSO>补充
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;

    // search?keyword=xxx
    @RequestMapping(path = "/search", method = RequestMethod.GET)
    public String search(Model model,
                         String keyword,
                         Page page)
    {
        //ES搜索 ：ESService出结果
        org.springframework.data.domain.Page<DiscussPost> searchResult =
                elasticsearchService.searchDiscussPostInES(keyword, page.getCurrent()-1,page.getLimit());

        //放入LM model
        List<Map<String,Object>> discussPosts = new ArrayList<>();
        if(searchResult!=null){
            //开始for：遍历取出 非n的
            for(DiscussPost post:searchResult){
                Map<String,Object> map = new HashMap<>();
                map.put("post",post);//ES查出的带em的核心放入

                //补充其他杂信息
                // 作者
                map.put("user", userService.findUserByid(post.getUserId()));
                // 点赞数量
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

                //塞入list
                discussPosts.add(map);//map在html中不出现，只出现String
            }
        }
        //杂把回显
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("keyword", keyword);

        //分页按钮（后期背，太乱，直接抄。。）
        page.setPath("/search?keyword=" + keyword);//page按钮复用url好笨的底层哈哈！
        page.setRows(searchResult==null? 0:(int)searchResult.getTotalElements());

        return "moban/site/search";

    }
}
